package user

import (
	"encoding/json"
	"time"

	"gitee.com/xgotool/backend-framework-template/config"
	"gitee.com/xgotool/backend-framework-template/model"
	"gitee.com/xiaoyutab/xgotool/individual/xginplus"
)

// 创建后台角色信息
//
//	POST	/user/role_create
func RoleCreate(c *xginplus.Context) *xginplus.Response {
	mod := model.Role{}
	if err := c.Bind(&mod); err != nil {
		return c.Error(err)
	}

	if len(mod.MenuIds) == 0 {
		return c.Errorf("抱歉，角色权限不能为空")
	}
	if mod.RoleName == "" {
		return c.Errorf("抱歉，角色名称不能为空")
	}
	conn, err := config.GetConnect()
	if err != nil {
		return c.Error(err)
	}
	if mod.Id > 0 {
		old := model.Role{}
		conn.Table(mod.TableName()).Where("id", mod.Id).Where("is_deleted", 0).Find(&old)
		if old.Id == 0 {
			return c.Errorf("角色未找到")
		}
		mod.CreatedAt = old.CreatedAt
	}
	mod.UpdatedAt = time.Now().Unix()
	b, _ := json.Marshal(mod.MenuIds)
	mod.RoleMenu = string(b)
	if err := conn.Table(mod.TableName()).Save(&mod).Error; err != nil {
		return c.Error(err)
	}
	return c.SuccessEmpty()
}
